package com.lhkj.ct.meta.modules.report.word.personal;

import com.lhkj.ct.base.exception.SystemException;
import com.lhkj.ct.base.utils.file.FileUtils;
import com.lhkj.ct.base.utils.file.word.xwpf.CustomXWPFDocument;
import com.lhkj.ct.meta.modules.psychology.model.entity.TblScaleReportContent;
import com.lhkj.ct.meta.modules.psychology.model.vo.PersonalReportInfo;
import org.apache.poi.xwpf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 描述
 * </p>
 *
 * @author job
 * @since 2023/10/22
 */
public class StandardReportHandle extends BaseLayoutHandler<PersonalReportInfo> {
    private static final Logger logger = LoggerFactory.getLogger(NormLayoutHandler.class);

    private PersonalReportInfo data;

    private static final Font globalFont = new Font("宋体", Font.PLAIN, 9);

    @Override
    protected void init() {
        try ( InputStream is = FileUtils.readResourceFile("report\\个体报告标准模板.docx")){
            document = new CustomXWPFDocument(is);
        } catch (IOException e) {
            logger.error("模板加载失败,原因：==>{}", e.getMessage());
            throw new SystemException("模板加载失败");
        }
    }

    @Override
    public XWPFDocument build(PersonalReportInfo data) {
        this.data = data;
        // 报告标题
        super.builderTitle(data.getScaleName());
        // 报告基本信息
        super.builderBasicInfoTable(data.getBasicInfo());
        // 维度报告
        generateReportTable();
        // 统计图表
        createChart();
        // 解释说明
        generateExplain();
        // 审核人签名
        document.getParagraphArray(7).setVerticalAlignment(TextAlignment.CENTER);
        super.sign(data.getBasicInfo(), document.getParagraphArray(7).getRuns().get(0));
        return document;
    }

    private void generateReportTable() {
        List<TblScaleReportContent> reportContents = data.getDimReport().stream()
                .filter(reportContent -> Objects.equals(1, reportContent.getDimType()))
                .collect(Collectors.toList());
        super.generateDimReportTable(document.getTableArray(1), reportContents);
    }

    private void createChart(){
        // step 4.绘制条形图
        try {
            BufferedImage image = data.getChart().getBuildChart().apply(data);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", os);
            document.createPicture(
                    document.addPictureData(new ByteArrayInputStream(os.toByteArray()), XWPFDocument.PICTURE_TYPE_JPEG),
                    1,
                    image.getWidth(),
                    image.getHeight(),
                    document.getParagraphArray(3));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void generateExplain() {
        Optional<TblScaleReportContent> first = data.getDimReport().stream()
                .filter(reportContent -> Objects.equals(2, reportContent.getDimType()))
                .findFirst();
        XWPFParagraph paragraphArray = document.getParagraphArray(5);
        paragraphArray.setIndentationFirstLine(567);
        XWPFRun run = paragraphArray.createRun();
        run.setFontFamily(globalFont.getFamily());
        run.setFontSize(globalFont.getSize());
        if (first.isPresent()) {
            TblScaleReportContent total = first.get();
            run.setText(String.format("总分为：%f。 %s", total.getRealScore().doubleValue(), total.getExplanation()));
        }else {
            run.setText("无");
        }
    }
}
